package GoodsService

import (
	"context"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/entity"
	"github.com/gogf/gf/encoding/gjson"
	"time"
)

func GetGoodsActivityRule(ctx context.Context, activityId int64) (*entity.GoodsActivityRule, error) {
	var goodsActivityRule entity.GoodsActivityRule
	err := toolsDb.GetUnSafaTable(ctx, "goods_activity_rule").
		// TODO: 临时缓存 60 秒
		Cache(60*time.Second).Where("activity_id = ?", activityId).Scan(&goodsActivityRule)
	if err != nil {
		return nil, err
	}
	return &goodsActivityRule, nil
}

// GetGoodsActivityRuleTuanTimeout 取出团购活动规则，自动关团时间
func GetGoodsActivityRuleTuanTimeout(ctx context.Context, activityId int64) (int64, error) {
	garModel, err := GetGoodsActivityRule(ctx, activityId)
	if err != nil {
		return 0, err
	}
	// 从JSON中取出自动关团时间
	json, err := gjson.LoadContent(garModel.Rules)
	if err != nil {
		return 0, err
	}
	tuanTimeout := json.GetInt64("timeout", 86400) // 如果没有找到配置，默认1天
	return tuanTimeout, nil
}

// GetGoodsActivityRuleTuanMaxNum 取出团购活动规则，成团人数
func GetGoodsActivityRuleTuanMaxNum(ctx context.Context, activityId int64) (int64, error) {
	garModel, err := GetGoodsActivityRule(ctx, activityId)
	if err != nil {
		return 0, err
	}
	// 从JSON中取出自动关团时间
	json, err := gjson.LoadContent(garModel.Rules)
	if err != nil {
		return 0, err
	}
	tuanTimeout := json.GetInt64("tuan_num")
	return tuanTimeout, nil
}

// GetGoodsActivityRuleTuanCloseTime 获取团购活动，关单时间 秒
func GetGoodsActivityRuleTuanCloseTime(ctx context.Context, activityId int64) (int64, error) {
	garModel, err := GetGoodsActivityRule(ctx, activityId)
	if err != nil {
		return 0, err
	}
	// 从JSON中取出自动关团时间
	json, err := gjson.LoadContent(garModel.Rules)
	if err != nil {
		return 0, err
	}
	tuanTimeout := json.GetInt64("close_time", 300) // 如果没有找到配置，默认5分钟
	return tuanTimeout, nil
}

// GetGoodsActivityRuleTuanLeaveNum 获取团购活动，缺少成团人数
func GetGoodsActivityRuleTuanLeaveNum(ctx context.Context, activityId int64, tuanJoinId string) (int64, error) {
	tuanMaxNum, err := GetGoodsActivityRuleTuanMaxNum(ctx, activityId)
	if err != nil {
		return 0, err
	}
	return tuanMaxNum - int64(getGoodsTuanNum(ctx, tuanJoinId, true)), nil
}
